package com.sunshine.lnuplusweb.controller;

import com.sunshine.lnuplusweb.service.UserConfigService;
import com.sunshine.lnuplusweb.service.UserService;
import com.sunshine.lnuplusweb.utils.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    //别忘了注入SpringBoot容器
    @Resource
    private UserService userService;

    @Resource
    private UserConfigService userConfigService;

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    //开始登录，接受post值
    //注意设置为ResponseBody来不响应thymeleaf
    @PostMapping("/login")
    @ResponseBody
    public Result toLogin(@RequestParam("userId") String userId,
                          @RequestParam("password") String password,
                          HttpSession httpSession) {
        //自定义返回实体类并且发送到前端，由前端ajax接受并处理
        Result result = new Result();
        if (userService.login(userId, password) == 1) {
            result.setResultCode(Result.RESULT_OK);
            //存储当前已经登录的用户
            httpSession.setAttribute("userId", userId);
        } else {
            result.setResultCode(Result.RESULT_NOT_FOUND);
        }
        return result;
    }

    @PostMapping("/register")
    @ResponseBody
    public Result toRegister(@RequestParam("userId") String userId,
                             @RequestParam("password") String password) {
        Result result = new Result();
        //该账户已经被注册
        if (userService.getUserCountById(userId) > 0) {
            result.setResultCode(Result.RESULT_SERVICE_ERROR);
        } else {
            userService.register(userId, password);
            //添加用户默认配置
            userConfigService.addDefaultConfig(userId);
            result.setResultCode(Result.RESULT_OK);
        }
        return result;
    }
}
